<template>
	<view class="container">
		<!-- 搜索框 -->
		<view class="search-container">
			<view class="search-box">
				<input class="search-input" placeholder="请输入医生姓名" v-model="queryParams.doctorName"
					@confirm="getDoctorsList" />
				<button class="search-btn" @click="getDoctorsList">搜索</button>
			</view>
		</view>

		<!-- 医生列表 -->
		<view class="doctor-list">
			<view class="doctor-item" v-for="(doctor, index) in doctorList" :key="index">
				<view class="doctor-info">
					<image class="doctor-doctorPhoto" :src="doctor.doctorPhoto" mode="aspectFill"></image>
					<view class="doctor-name">{{ doctor.doctorName }}</view>
				</view>
				<button class="appointment-btn" @click="showAppointmentModal(doctor)">
					预约
				</button>
			</view>

			<!-- 分页控件 -->
			<view class="pagination">
				<button class="page-btn" @click="prevPage" :disabled="queryParams.pageNo === 1">
					上一页
				</button>
				<text class="page-info">
					第 {{ queryParams.pageNo }} 页，共 {{ totalPages }} 页
				</text>
				<button class="page-btn" @click="nextPage" :disabled="queryParams.pageNo === totalPages">
					下一页
				</button>
			</view>
		</view>

		<!-- 预约弹框 -->
		<view class="modal" v-if="showModal">
			<view class="modal-content">
				<view class="modal-header">
					<text class="modal-title">预约挂号</text>
				</view>
				<view class="modal-body">
					<view class="doctor-details">
						<image class="modal-doctor-doctorPhoto" :src="selectedDoctor.doctorPhoto" mode="aspectFill">
						</image>
						<text class="modal-doctor-name">{{ selectedDoctor.doctorName }}</text>
					</view>
					<view class="appointment-form">
						<view class="form-item">
							<text class="form-label">预约时间:</text>
							<uv-datetime-picker ref="datetimePicker" v-model="appointmentForm.appointDate"
								mode="datetime" :minDate="minDate" :maxDate="maxDate"
								@confirm="confirm"></uv-datetime-picker>
							<button @click="open">{{ formatDate(appointmentForm.appointDate) || '请选择预约时间' }}</button>
						</view>
						<view class="form-item">
							<text class="form-label">备注:</text>
							<textarea class="form-textarea" placeholder="请输入备注信息"
								v-model="appointmentForm.remarks"></textarea>
						</view>
					</view>
				</view>
				<view class="modal-footer">
					<button class="cancel-btn" @click="closeModal">取消</button>
					<button class="confirm-btn" @click="confirmAppointment">确认</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		onMounted
	} from 'vue';
	
	
	// 格式化时间戳为可读的日期格式
	const formatDate = (timestamp) => {
		if (!timestamp) return '';
		const date = new Date(timestamp);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		return `${year}-${month}-${day} ${hours}:${minutes}`;
	};

	// 查询参数
	const queryParams = reactive({
		pageNo: 1,
		pageSize: 5,
		doctorName: '',
		status: 1
	});

	// 医生列表数据
	const doctorList = ref([]);

	// 总页数
	const totalPages = ref(1);

	// 是否显示预约弹框
	const showModal = ref(false);

	// 当前选中的医生
	const selectedDoctor = reactive({
		id: null,
		doctorCode: '',
		doctorName: '',
		doctorPhoto: ''
	});

	// 预约表单数据
	const appointmentForm = reactive({
		clientCode: '',
		clientName: '',
		doctorCode: '',
		doctorName: '',
		appointDate: '',
		remarks: ''
	});

	// 当前时间的时间戳
	const currentTimestamp = new Date().getTime();

	// 最小日期时间（当前系统时间）
	const minDate = ref(currentTimestamp);

	// 最大日期时间（当前系统时间加15天）
	const maxDate = ref(currentTimestamp + 15 * 24 * 60 * 60 * 1000);

	// 日期选择器引用
	const datetimePicker = ref(null);

	// 打开日期选择器
	const open = () => {
		datetimePicker.value.open();
	};

	// 确认选择
	const confirm = (e) => {
		console.log('confirm', e);
		appointmentForm.appointDate = e.detail.value;
	};

	// 显示预约弹框
	const showAppointmentModal = (doctor) => {
		Object.assign(selectedDoctor, doctor);
		showModal.value = true;
	};

	// 关闭预约弹框
	const closeModal = () => {
		showModal.value = false;
	};

	// 确认预约
	const confirmAppointment = () => {
		// 验证预约时间是否为空
		if (!appointmentForm.appointDate) {
			uni.showToast({
				title: '请选择预约时间',
				icon: 'none'
			});
			return;
		}

		// 调用预约接口
		uni.request({
			url: 'http://localhost:58080/admin-api/base/appoint-data/create', // 预约接口地址
			method: 'POST',
			data: {
				clientCode: appointmentForm.clientCode,
				clientName: appointmentForm.clientName,
				doctorCode: selectedDoctor.doctorCode,
				doctorName: selectedDoctor.doctorName,
				appointDate: appointmentForm.appointDate,
				remarks: appointmentForm.remarks
			},
			header: {
				'Content-Type': 'application/json', // 设置请求头
				// 如果需要携带 token，可以从本地存储中获取并设置到请求头中
				'Authorization': `Bearer ${uni.getStorageSync('userInfo').accessToken}`
			},
			success: (res) => {
				if (res.data.code === 0) {
					// 预约成功
					uni.showToast({
						title: '预约成功',
						icon: 'success'
					});
					// 重置表单和弹框
					Object.assign(appointmentForm, {
						doctorCode: '',
						doctorName: '',
						appointDate: '',
						remarks: ''
					});
					closeModal();
				} else {
					// 预约失败
					uni.showToast({
						title: res.data.msg || '预约失败',
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				// 请求失败
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				});
				console.error(err);
			}
		});
	};



	// 处理页码变更
	const prevPage = () => {
		if (queryParams.pageNo > 1) {
			queryParams.pageNo--;
			getDoctorsList();
		}
	};

	const nextPage = () => {
		if (queryParams.pageNo < totalPages.value) {
			queryParams.pageNo++;
			getDoctorsList();
		}
	};

	// 页面加载时初始化
	onMounted(() => {
		getDoctorsList();
		getUserProfile();
	});

	// 获取医生列表
	const getDoctorsList = () => {
		uni.request({
			url: 'http://localhost:58080/admin-api/base/doctorinfo-data/page',
			method: 'GET',
			data: {
				pageNo: queryParams.pageNo,
				pageSize: queryParams.pageSize,
				doctorName: queryParams.doctorName,
				status: queryParams.status
			},
			header: {
				'Content-Type': 'application/json',
				// 如果需要携带 token，可以从本地存储中获取并设置到请求头中
				'Authorization': `Bearer ${uni.getStorageSync('userInfo').accessToken}`
			},
			success: (res) => {
				if (res.data.code === 0) {
					// 假设接口返回的数据结构是 { data: { list: [], total: number } }
					const response = res.data;
					if (response.code === 0) { // 根据实际接口返回的结构进行调整
						doctorList.value = response.data.list;
						totalPages.value = Math.ceil(response.data.total / queryParams.pageSize);
					} else {
						uni.showToast({
							title: response.msg || '获取医生列表失败',
							icon: 'none'
						});
					}
				} else {
					uni.showToast({
						title: '获取医生列表失败',
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				});
				console.error(err);
			}
		});
	};

	// 获取用户信息
	const getUserProfile = () => {
		uni.request({
			url: 'http://localhost:58080/admin-api/system/user/profile/get', // 获取用户信息接口地址
			method: 'GET',
			header: {
				'Content-Type': 'application/json',
				// 如果需要携带 token，可以从本地存储中获取并设置到请求头中
				'Authorization': `Bearer ${uni.getStorageSync('userInfo').accessToken}`
			},
			success: (res) => {
				if (res.data.code === 0) {
					//赋值预约表单个人信息
					const profileData = res.data.data;
					appointmentForm.clientCode = profileData.username;
					appointmentForm.clientName = profileData.nickname;
				} else {
					// 获取用户信息失败
					uni.showToast({
						title: res.data.msg || '获取用户信息失败',
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				// 请求失败
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				});
				console.error(err);
			}
		});
	};
</script>

<style scoped>
	.container {
		padding: 20px;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	/* 搜索框样式 */
	.search-container {
		margin-bottom: 20px;
	}

	.search-box {
		display: flex;
		border: 1px solid #ddd;
		border-radius: 5px;
		overflow: hidden;
	}

	.search-input {
		flex: 1;
		height: 40px;
		padding: 0 10px;
		font-size: 14px;
	}

	.search-btn {
		width: 60px;
		height: 40px;
		background-color: #1aad19;
		color: white;
		border: none;
		font-size: 14px;
	}

	/* 医生列表样式 */
	.doctor-list {
		background-color: #fff;
		border-radius: 10px;
		padding: 15px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
	}

	.doctor-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px 0;
		border-bottom: 1px solid #f0f0f0;
	}

	.doctor-info {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.doctor-doctorPhoto {
		width: 80px;
		height: 80px;
		border-radius: 50%;
		margin-bottom: 10px;
		border: 2px solid #fff;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
	}

	.doctor-name {
		font-size: 16px;
		font-weight: bold;
		color: #333;
	}

	.appointment-btn {
		width: 80px;
		height: 35px;
		margin-right: 5px;
		background-color: #55aaff;
		color: white;
		border: none;
		border-radius: 5px;
		font-size: 14px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	/* 分页样式 */
	.pagination {
		margin-top: 20px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.page-btn {
		width: 80px;
		height: 30px;
		margin: 0 10px;
		background-color: #f5f5f5;
		border: 1px solid #ddd;
		border-radius: 5px;
		font-size: 14px;
	}

	.page-info {
		font-size: 14px;
		color: #666;
	}

	/* 弹框样式 */
	.modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}

	.modal-content {
		background-color: #fff;
		border-radius: 10px;
		width: 80%;
		max-width: 500px;
		overflow: hidden;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px 20px;
		border-bottom: 1px solid #f0f0f0;
	}

	.modal-title {
		font-size: 18px;
		font-weight: bold;
		color: #333;
	}

	.close-btn {
		color: #999;
		font-size: 16px;
		background: none;
		border: none;
		cursor: pointer;
	}

	.modal-body {
		padding: 20px;
	}

	.doctor-details {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 20px;
	}

	.modal-doctor-doctorPhoto {
		width: 100px;
		height: 100px;
		border-radius: 50%;
		margin-bottom: 10px;
		border: 2px solid #fff;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
	}

	.modal-doctor-name {
		font-size: 18px;
		font-weight: bold;
		color: #333;
	}

	.appointment-form {
		width: 100%;
	}

	.form-item {
		margin-bottom: 20px;
	}

	.form-label {
		display: block;
		margin-bottom: 8px;
		font-size: 16px;
		color: #333;
	}

	.picker-placeholder {
		width: 90%;
		height: 40px;
		border: 1px solid #ddd;
		border-radius: 5px;
		padding: 0 10px;
		font-size: 14px;
		display: flex;
		align-items: center;
	}

	.form-textarea {
		width: 90%;
		height: 80px;
		border: 1px solid #ddd;
		border-radius: 5px;
		padding: 10px;
		font-size: 14px;
	}

	.modal-footer {
		display: flex;
		justify-content: flex-end;
		padding: 15px 20px;
		border-top: 1px solid #f0f0f0;
	}

	.cancel-btn {
		width: 100px;
		height: 40px;
		background-color: #f5f5f5;
		border: 1px solid #ddd;
		border-radius: 5px;
		color: #666;
		font-size: 14px;
		margin-right: 10px;
	}

	.confirm-btn {
		width: 100px;
		height: 40px;
		background-color: #1aad19;
		color: white;
		border: none;
		border-radius: 5px;
		font-size: 14px;
	}
</style>